﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using General;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace Client
{
    struct vitri
    {
        public int luot;
    }
    public partial class FormChat : Form
    {
        IRemote obj;
        String Username;
        int  vitrigo;
        char kytugo;
        char kytutext;
        int len;
        WrapperTransporterClass wtc1;
        string[] usernames;
        int count;
        vitri[,] hai = new vitri[21, 21];
        int[,] mag = new int[19, 19];
        int h, c;
        int h1, c1;
        int flags; 
        int winm;
        int winho; 
        Boolean luot = false;
        string Doithuhientai;
        int tralaiTextdoithu;
        int dachapnhan;
        int danhchu;
        int diemm; 
        int diemdt;
        int k;
        int thoigian = 120;
        public FormChat(IRemote obj, String Username)
        {
            InitializeComponent();
           
            AcceptButton = btnSend;
            this.obj = obj;

            this.Username = Username;
            this.Text = Username;

            wtc1 = new WrapperTransporterClass();
            RegisterMethodToWrapperTransporterClass();


            obj.RegisterWrapperTransporterClass(Username, wtc1);

            for (int i = 0; i < 19; i++)
                for (int j = 0; j < 19; j++)
                    mag[i, j] = 0;
            for (int i = 0; i <= 20; i++)
                for (int j = 0; j <= 20; j++)
                    hai[i, j].luot = 2;
            flags = 2;
            winm = 0;
            winho = 0;
            Doithuhientai = "";
            tralaiTextdoithu = 0;
            dachapnhan = 0;
            label3.Text = this.Username;
            label6.Text = diemm.ToString();
            danhchu = 0;
            diemm = 0;
            diemdt = 0;
            usernames = new string[1200];
            usernames[0] = "hai";
            count = 0;
            k = 0;
           
        }

        private void DoNothingInCallBack(IAsyncResult Res) { }

        private void RegisterMethodToWrapperTransporterClass()
        {
            wtc1.SendvaluePrivateTransporterDelegate += ValueReceivedHandler;
        }
        delegate void DelegateSendMessageToServer(String Sender, String MsgCont);// gỏi Mesage đến Server
        delegate void DelegateSendValuePrivate(String Sender, String Receiver, int type, int x, int y, int who, String Msg);// gỏi data đến Server- Sever gởi lại cho Peceiver
        private void  ValueReceivedHandler(String Sender, int type, int x, int y, int who, String Msg)
        {
            if (type == 1 && Doithuhientai.Equals(Sender))
            {
               
                winho = who;
                luot = true;
               
                thoigian = 120;//det Tg =120s;
            }
            if (type == 0)
            {
                AddTextToChatDisplay(Sender + " :" + Msg);
                btnSend.BackColor = System.Drawing.Color.Yellow;
            }
            if (type == 2)
            {
                MessageBox.Show("Erro!không thể chát với :" + Msg);
            }
            if (type == 3)
            {
                if (MessageBox.Show(Sender + " Muốn chơi Game với bạn ", "Ok", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    Doithuhientai = Sender;
                    luot = true;
                    dachapnhan = 1;
                    danhchu = 1;
                    diemm = 0; diemdt = 0;
                   
                    thoigian = 120;//set Tg =120s;
                }
                else
                { 
                    DelegateSendValuePrivate dsmts = new DelegateSendValuePrivate(obj.SendValuePrivate);
                    dsmts.BeginInvoke(Username, Sender, 4, 0, 0, winm, null, new AsyncCallback(DoNothingInCallBack), null);
                }
            }
            if (type == 4)
            {
                MessageBox.Show(Sender + " không chấp nhận chơi !");
                tralaiTextdoithu = 1;
            }
            if (type == 5)
            {
                MessageBox.Show("không thể kết nối với : " + Msg);
                tralaiTextdoithu = 1;
            }
            if (type == 6)
            {
               
                if (!Msg.Equals(Sender))
                {
                    for (int j = 0; j <= count; j++)
                    {
                        if (Msg.Equals(usernames[j]))
                        {
                            break;
                        }
                        if (j == count)
                        {

                            usernames[count] = Msg;
                            count++;
                            break;
                        }
                    }
                }
            }
            if (type == 7)
            {
                AddTextToChatDisplay(Sender + "Đã đánh bại " + Msg);
                
            }
            if (type == 8)
            {
                MessageBox.Show("Đã thắng do đối thủ hết h. Click để đánh ván khác");
                winho = who;
                luot = true;
               
            }
            if (type == 9)
            {
                MessageBox.Show("Cố lên !");
                k = 0;
                luot =true;
                thoigian = 120;//tra thoi gain ve 120s
            }
        }//nhận data từ sever
        /// <summary>
        /// quan ly cac button va label
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSend_Click(object sender, EventArgs e)
        {
            if (txtChatInput.Text != null && txtChatInput.Text.Length > 0)
            {
                AddTextToChatDisplay(Username + ": " + txtChatInput.Text);

                if (txtChatWith.Text.Equals("_SERVER", StringComparison.CurrentCultureIgnoreCase))
                {
                    //obj.SendMessageToServer(Username, txtChatInput.Text);
                    
                }
                else
                {

                    DelegateSendValuePrivate dsmts = new DelegateSendValuePrivate(obj.SendValuePrivate);
                    dsmts.BeginInvoke(Username, txtChatWith.Text, 0, 0, 0, winm, txtChatInput.Text, new AsyncCallback(DoNothingInCallBack), null);

                }
                txtChatInput.Clear();
            }
        }
        private void OK_Click(object sender, EventArgs e)// su kien kick nut Ok
        {
            try
            {
                Doithuhientai = comboBox1.SelectedItem.ToString();
            }
            catch (Exception e1)
            { }

            //lbTimer.Visible = true;
            OK.Visible = false;
            label4.Text = Doithuhientai;
            label5.Text = diemdt.ToString();
            danhchu = 0;// danh quan 0
            reset();
            luot = false;
            DelegateSendValuePrivate dsmts = new DelegateSendValuePrivate(obj.SendValuePrivate);
            dsmts.BeginInvoke(Username, Doithuhientai, 3, 0, 0, winm, null, new AsyncCallback(DoNothingInCallBack), null);
        }
        private void txtChatInput_TextChanged(object sender, EventArgs e)
        {
            this.btnSend.BackColor = System.Drawing.Color.Ivory;
            //tra btSend ve mau trang 
        }
        delegate void AddTextToDisplayDelegate(String Cont);
        private void AddTextToChatDisplay(String Cont)
        {
            if (this.InvokeRequired)
            {
                AddTextToDisplayDelegate d = new AddTextToDisplayDelegate(AddTextToChatDisplay);
                this.Invoke(d, Cont);
            }
            else
            {
                txtChatDisplay.AppendText(Cont + Environment.NewLine);
            }
        }

        private void FormChat_Load(object sender, EventArgs e)
        {
            timer.Stop();
            Reset();
        }

        
        private void comboBox1_oneClick(object sender, EventArgs e)
        {
            comboBox1.Items.Clear();
            DelegateSendValuePrivate dsmts = new DelegateSendValuePrivate(obj.SendValuePrivate);
            dsmts.BeginInvoke(Username, null, 6, 0, 0, winm, null, new AsyncCallback(DoNothingInCallBack), null);
            
            for (int j = 0; j < count; j++)
                comboBox1.Items.Add(usernames[j]);
        }//ve khi minh đánh..... có kiem tra thang thua
        void reset()//bat dau vong choi #
        {
            for (int i = 0; i <= 20; i++)
                for (int j = 0; j <= 20; j++)
                    hai[i, j].luot = 2;
            for (int i = 0; i < 19; i++)
                for (int j = 0; j < 19; j++)
                    mag[i, j] = 0;
            flags = 1;
            winho = 0;

            label6.Text = diemm.ToString();
            label5.Text = diemdt.ToString();
            thoigian = 120;//set thoi gian =120;
        }
        //Dong ho dem h
        int count1 = 0;
        int count2 = 0;
        private void timer1_Tick_1(object sender, EventArgs e)
        {
            if (btnStart.Text == "Start")
            {
                thoigian--;
                int t = thoigian * 100 / 120;
                t = t > 0 ? t : 0;
                // progressBar1.Value=thoigian>0?thoigian:0;
                lbTime.Text = t + "s";
                if (thoigian == 0 && k != 0)
                {
                    if (luot)
                    {
                        DelegateSendValuePrivate dsmts = new DelegateSendValuePrivate(obj.SendValuePrivate);
                        dsmts.BeginInvoke(Username, Doithuhientai, 8, 0, 0, 2, null, new AsyncCallback(DoNothingInCallBack), null);
                        MessageBox.Show("Thời gian đã hết bạn thua rồi");
                        diemdt++;
                        danhchu = 1;
                        reset();
                        luot = false;
                    }
                }
            }
        }
        private void Reset()
        {
            thoigian = 120;
            vitrigo = 0;
            Random rd = new Random();
            string filename = "BaiGo" + rd.Next(1, 4) + ".txt";
            StreamReader sr = new StreamReader(File.OpenRead(filename));
            
            this.NoiDung.Text = sr.ReadToEnd();
            len = this.NoiDung.Text.Length;
            this.NoiDung.Select(vitrigo, 1);
          //  this.progressBar1.Value = thoigian;
            //this.lbTimer.Text = thoigian;
            this.timer.Start();
            this.btnChoiLai.Visible = true;

        }
        private void FormChat_KeyPress(object sender, KeyPressEventArgs e)
        {
            kytugo = e.KeyChar;
            kytutext = this.NoiDung.Text[vitrigo];
            if (kytutext == kytugo)
            {
                vitrigo++;
                if (vitrigo == len)
                {
                    MessageBox.Show("Bạn đã thắng cuộc ");
                    this.btnChoiLai.Visible = true;
                    this.timer.Stop();
                    this.NoiDung.Text = "";
                }
                else
                    this.NoiDung.Select(vitrigo, 1);

            }
        }

        private void btnChoiLai_Click(object sender, EventArgs e)
        {
            DialogResult dlg = MessageBox.Show("Bạn chấp nhận thua ? ", "Message", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dlg == DialogResult.OK)
            {
                Reset();

            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {

            count1++;
            if (count1 == 60)
            {
                count2++;
                count1 = 0;
            }
            string phut = count2.ToString();

            string giay = count1.ToString();
            //string tichtac = DateTime.Now.Millisecond.ToString();
            lbTime.Text = phut + " :" + giay;
        }

        private void NoiDung_MouseMove(object sender, MouseEventArgs e)
        {
            
           
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            this.timer.Start();
        }

        private void lbTime_Click(object sender, EventArgs e)
        {
            
        }

    }
}
